<template>
  <router-view v-if="route.matched.length === 3" @updated="handleUpdated" />
  <div v-else class="info-container" style="width: 100%">
    <a-spin :spinning="loading1" tip="Loading...">
      <e-container v-permission="'FinancialInformation:Basic:Query'">
        <a-space>
          <e-title title="Financial Settings" />
          <a-divider type="vertical" />
          <a-button
            v-permission="'FinancialInformation:Basic:Edit'"
            type="link"
            size="small"
            @click="() => router.push({ name: 'Financial Settings' })"
          >
            <a-space>
              <e-icon type="edit" />
              Edit
            </a-space>
          </a-button>
        </a-space>
        <div class="table">
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">Payment Option</a-col>
            <a-col :span="5" :xxl="7" class="cell value">
              {{ Utils.transformNullValue(basicInfoData.paymentMethodName) }}
            </a-col>
            <a-col :span="7" :xxl="5" class="cell field">
              <e-field-tooltip
                filed-name="Prepayment"
                tips="Specifies whether the account is a pre-payment account; If yes, pre-payment account will be used as a virtual wallet, and project invoices would deduct directly from the prepaid amount."
              />
            </a-col>
            <a-col :span="5" :xxl="7" class="cell value">
              {{ Utils.transformNullValue(boolToYesOrNo(basicInfoData.isAdvance)) }}
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">
              <e-field-tooltip
                filed-name="Monthly Combined Invoice"
                tips="Specifies whether to aggregate invoices on a monthly basis; If yes, the approved invoices will be aggregated and managed monthly, and Finance would send a combined invoice for the month."
              />
            </a-col>
            <a-col :span="5" :xxl="7" class="cell value">
              {{ Utils.transformNullValue(boolToYesOrNo(basicInfoData.isMonthPayment)) }}
            </a-col>
            <a-col :span="7" :xxl="5" class="cell field">
              <e-field-tooltip
                filed-name="Month-End Invoice Date"
                tips="Specifies whether to generate the invoices at the month-end; If yes, the invoice will be generated and dated as of month-end."
              />
            </a-col>
            <a-col :span="5" :xxl="7" class="cell value">
              {{ Utils.transformNullValue(boolToYesOrNo(basicInfoData.isInvoiceFileDate)) }}
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">
              <e-field-tooltip
                filed-name="Electronic Invoice (Send Email)"
                tips="Specifies whether to generate electronic invoice; typically yes for non-PRC clients."
              />
            </a-col>
            <a-col :span="5" :xxl="7" class="cell value">
              {{ Utils.transformNullValue(boolToYesOrNo(basicInfoData.isEleInvoice)) }}
            </a-col>
            <a-col :span="7" :xxl="5" class="cell field">
              <e-field-tooltip
                filed-name="Auto-send Invoice"
                tips="Specifies whether to automatically send the invoice once approved."
              />
            </a-col>
            <a-col :span="5" :xxl="7" class="cell value">
              {{ Utils.transformNullValue(boolToYesOrNo(basicInfoData.isAutoSentInvoice)) }}
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">
              <e-field-tooltip
                filed-name="Online Invoice (via client preferred portal)"
                tips="Specifies whether to upload the invoice using a client portal. Typically no, unless otherwise specified by client."
              />
            </a-col>
            <a-col :span="5" :xxl="7" class="cell value">
              {{ Utils.transformNullValue(boolToYesOrNo(basicInfoData.isOnlineInvoice)) }}
            </a-col>
            <a-col :span="7" :xxl="5" class="cell field">
              <e-field-tooltip
                filed-name="Taxation Invoice"
                tips="Specifies whether to send a taxation invoice. Typically no, unless for a PRC client.VAT invoices should be send paper."
              />
            </a-col>
            <a-col :span="5" :xxl="7" class="cell value">
              {{ basicInfoData.isPaperInvoice ? basicInfoData.paperInvoiceTypeName : 'No' }}
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">
              <e-field-tooltip
                filed-name="Payment Reminder"
                tips="Specifies whether acceptable to send payment reminder."
              />
            </a-col>
            <a-col :span="5" :xxl="7" class="cell value">
              {{ Utils.transformNullValue(boolToYesOrNo(basicInfoData.isReminder)) }}
            </a-col>
            <a-col :span="7" :xxl="5" class="cell field">
              <e-field-tooltip
                filed-name="Auto-send Reminder"
                tips="Specifies whether to automatically send payment reminder for invoices past due by 45 days. Sent every month on the 21st."
              />
            </a-col>
            <a-col :span="5" :xxl="7" class="cell value">
              {{ Utils.transformNullValue(boolToYesOrNo(basicInfoData.isAutoReminder)) }}
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">Tax Rate (%)</a-col>
            <a-col :span="17" :xxl="19" class="cell value" style="word-wrap: break-word">
              {{ basicInfoData.clientTax === null ? '--' : (basicInfoData.clientTax * 100).toFixed(0) + '%' }}
            </a-col>
          </a-row>
          <a-row style="min-height: 80px">
            <a-col :span="7" :xxl="5" class="cell field">External Invoice Note</a-col>
            <a-col :span="17" :xxl="19" class="cell value" style="word-wrap: break-word">
              {{ Utils.transformNullValue(basicInfoData.externalNote) }}
            </a-col>
          </a-row>
          <a-row style="min-height: 80px">
            <a-col :span="7" :xxl="5" class="cell field">Internal Invoice Note</a-col>
            <a-col :span="17" :xxl="19" class="cell value" style="word-wrap: break-word">
              {{ Utils.transformNullValue(basicInfoData.internalNote) }}
            </a-col>
          </a-row>
        </div>
      </e-container>
    </a-spin>
    <a-spin v-show="basicInfoData.isPaperInvoice" :spinning="loading3" tip="Loading...">
      <e-container v-permission="'FinancialInformation:Basic:Query'">
        <a-space>
          <e-title title="Tax Info" />
          <a-divider type="vertical" />
          <a-button
            v-permission="'FinancialInformation:Basic:Edit'"
            type="link"
            size="small"
            @click="() => router.push({ name: 'Tax Info' })"
          >
            <a-space>
              <e-icon type="edit" />
              Edit
            </a-space>
          </a-button>
        </a-space>
        <div class="table">
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">ID No. of Taxpayer (纳税人识别号)</a-col>
            <a-col :span="17" :xxl="19" class="cell value">{{
              Utils.transformNullValue(taxInfoData.taxpayerNumber)
            }}</a-col>
          </a-row>
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">Address & Telephone (地址和电话)</a-col>
            <a-col :span="17" :xxl="19" class="cell value">{{
              Utils.transformNullValue(taxInfoData.paperInvoiceAddressTel)
            }}</a-col>
          </a-row>
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">Opening Bank & Account Number (开户行和账号)</a-col>
            <a-col :span="17" :xxl="19" class="cell value">{{
              Utils.transformNullValue(taxInfoData.clientAccountBankNumber)
            }}</a-col>
          </a-row>
        </div>
      </e-container>
    </a-spin>
    <a-spin :spinning="loading1" tip="Loading...">
      <e-container v-permission="'FinancialInformation:BillingCycle:Query'">
        <a-space>
          <e-title title="Payment Settings" />
          <a-divider type="vertical" />
          <a-button
            v-permission="'FinancialInformation:BillingCycle:Edit'"
            type="link"
            size="small"
            @click="() => router.push({ name: 'Payment Settings' })"
          >
            <a-space>
              <e-icon type="edit" />
              Edit
            </a-space>
          </a-button>
        </a-space>
        <div class="table">
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">Currency</a-col>
            <a-col :span="5" :xxl="7" class="cell value">
              {{ Utils.transformNullValue(paymentSettings.currencyName) }}
            </a-col>
            <a-col :span="7" :xxl="5" class="cell field">Billing Cycle (Days)</a-col>
            <a-col :span="5" :xxl="7" class="cell value">
              {{ Utils.transformNullValue(paymentSettings.payCycle) }}
            </a-col>
          </a-row>
          <a-row v-if="paymentSettings.payCycle > 45">
            <a-col :span="7" :xxl="5" class="cell field">Attachment</a-col>
            <a-col :span="17" :xxl="19" class="cell value">
              <a-tag
                v-if="paymentSettings.payCycleAttachID"
                style="cursor: pointer"
                class="attachment-tag"
                @click="handleDownload(paymentSettings.attachmentAddr, paymentSettings.attachmentName)"
              >
                <a-space><e-icon type="Document" />{{ paymentSettings.attachmentName }}</a-space>
              </a-tag>
              <span v-else>--</span>
            </a-col>
          </a-row>
        </div>
      </e-container>
    </a-spin>
    <a-spin :spinning="loading1" tip="Loading...">
      <e-container v-permission="'FinancialInformation:Mail:Query'">
        <a-space>
          <e-title title="Mail Settings" />
          <a-divider type="vertical" />
          <a-button
            v-permission="'FinancialInformation:Mail:Edit'"
            type="link"
            size="small"
            @click="() => router.push({ name: 'Mail Settings' })"
          >
            <a-space>
              <e-icon type="edit" />
              Edit
            </a-space>
          </a-button>
        </a-space>
        <div class="table">
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">Invoice File Email To</a-col>
            <a-col :span="17" :xxl="19" class="cell value">
              <a-row v-if="mailSettings.to.length > 0" :gutter="[8, 8]">
                <a-col
                  v-for="(name, index) in mailSettings.to"
                  :key="index"
                  :span="4"
                  :title="name"
                  style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap"
                >
                  {{ name }}
                </a-col>
              </a-row>
              <span v-else>--</span>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">Invoice File Email Cc</a-col>
            <a-col :span="17" :xxl="19" class="cell value">
              <a-row v-if="mailSettings.cc.length > 0" :gutter="[8, 8]">
                <a-col
                  v-for="(name, index) in mailSettings.cc"
                  :key="index"
                  :span="4"
                  :title="name"
                  style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap"
                >
                  {{ name }}
                </a-col>
              </a-row>
              <span v-else>--</span>
            </a-col>
          </a-row>
        </div>
      </e-container>
    </a-spin>
    <a-spin :spinning="loading1" tip="Loading...">
      <e-container v-permission="'FinancialInformation:Factor:Query'">
        <a-space>
          <e-title title="Factor Settings" />
          <a-divider type="vertical" />
          <a-button
            v-permission="'FinancialInformation:Factor:Edit'"
            type="link"
            size="small"
            @click="() => router.push({ name: 'Factor Settings' })"
          >
            <a-space>
              <e-icon type="edit" />
              Edit
            </a-space>
          </a-button>
        </a-space>
        <div class="table">
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">Client Factor</a-col>
            <a-col :span="5" :xxl="7" class="cell value">{{
              Utils.transformNullValue(basicInfoData.clientCoefficient)
            }}</a-col>
            <a-col :span="7" :xxl="5" class="cell field">Commission Factor</a-col>
            <a-col :span="5" :xxl="7" class="cell value">{{
              Utils.transformNullValue(basicInfoData.priceCoefficient)
            }}</a-col>
          </a-row>
        </div>
      </e-container>
    </a-spin>
    <a-spin :spinning="loading2" tip="Loading...">
      <e-container v-permission="'FinancialInformation:BackInfo:Query'">
        <a-space>
          <e-title title="Bank Info" />
          <a-divider type="vertical" />
          <a-button v-permission="'FinancialInformation:BackInfo:Edit'" type="link" size="small" @click="editBankInfo">
            <a-space>
              <e-icon type="edit" />
              Edit
            </a-space>
          </a-button>
        </a-space>
        <div class="table">
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">Invoice Entity</a-col>
            <a-col :span="17" :xxl="19" class="cell value">
              {{ Utils.transformNullValue(bankInfoData.companyName) }}
              <span style="color: #bfbfbf; margin-left: 10px">{{
                Utils.transformNullValue(bankInfoData.companyNameEN)
              }}</span>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">Invoice Address</a-col>
            <a-col :span="17" :xxl="19" class="cell value">{{
              Utils.transformNullValue(bankInfoData.pdfCompanyName)
            }}</a-col>
          </a-row>
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">Contact Number</a-col>
            <a-col :span="5" :xxl="7" class="cell value">{{
              Utils.transformNullValue(bankInfoData.pdfCompanyTel)
            }}</a-col>
            <a-col :span="7" :xxl="5" class="cell field">Fax</a-col>
            <a-col :span="5" :xxl="7" class="cell value">{{
              Utils.transformNullValue(bankInfoData.pdfCompanyFax)
            }}</a-col>
          </a-row>
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">Invoice Template</a-col>
            <a-col :span="17" :xxl="19" class="cell value">{{
              Utils.transformNullValue(bankInfoData.invoiceTemplateName)
            }}</a-col>
          </a-row>
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">Address</a-col>
            <a-col :span="17" :xxl="19" class="cell value">{{
              Utils.transformNullValue(bankInfoData.pdfCompanyAddress)
            }}</a-col>
          </a-row>
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">Invoice Bank Account</a-col>
            <a-col :span="17" :xxl="19" class="cell value">{{
              Utils.transformNullValue(bankInfoData.bankAccount)
            }}</a-col>
          </a-row>
          <a-row>
            <a-col :span="7" :xxl="5" class="cell field">Invoice Details</a-col>
            <a-col :span="17" :xxl="19" class="cell value" style="min-height: 80px">
              <div v-if="bankInfoData.bankAccountDetail" v-html="bankInfoData.bankAccountDetail"></div>
              <div v-else>--</div>
            </a-col>
          </a-row>
        </div>
        <a-divider />
        <a-table
          :columns="columns"
          :data-source="data"
          class="ant-table-striped"
          :pagination="false"
          :row-class-name="(_record, index) => (index % 2 === 0 ? 'table-striped' : null)"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'beforeAccount'">
              <a @click="showBankInfo(record.beforeAccountID)">{{ record.beforeAccount }}</a>
            </template>
            <template v-if="column.key === 'afterAccount'">
              <a @click="showBankInfo(record.afterAccountID)">{{ record.afterAccount }}</a>
            </template>
          </template>
          <template #emptyText>
            <e-empty>
              <template #description>
                <div>No Data</div>
              </template>
            </e-empty>
          </template>
        </a-table>
      </e-container>
    </a-spin>
    <a-modal v-model:visible="visible" wrap-class-name="primary-modal" width="888px" title="View Bank Info">
      <a-form ref="formRef" layout="vertical">
        <a-row justify="space-between">
          <a-col :span="10">
            <a-form-item label="Invoice Bank Account" name="bankNo">
              <a-input v-model:value="formState.accountName" autocomplete="off" disabled></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item label="Branch">
              <a-input v-model:value="formState.accountCompanyName" autocomplete="off" disabled></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <span style="color: #818d9f; font-size: 14px">Invoice Details</span>
            <div class="information" v-html="formState.accountInformation"></div>
          </a-col>
        </a-row>
      </a-form>
      <template #footer>
        <a-button key="back" @click="handleCancel">Cancel</a-button>
        <a-button key="submit" type="primary" @click="handleCancel">Save</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'
import Utils from '@/utils'
import f from '@/api/client/financial.js'
import EContainer from '@/components/EContainer.vue'
import EIcon from '@/components/EIcon.vue'
import ETitle from '@/components/ETitle.vue'
import useDownload from '@/hooks/useDownload.js'
import Config from '@/config/index.js'
import EFieldTooltip from '@/components/EFieldTooltip.vue'
const { Modal } = inject('Feedback')
const route = useRoute()
const router = useRouter()
const { id } = route.params
const loading1 = ref(false)
const loading2 = ref(false)
const loading3 = ref(false)
const boolToYesOrNo = bool => {
  return bool ? 'Yes' : 'No'
}
const handleUpdated = () => {
  getBasicInfo()
  getPaymentSettings()
  getBankInfo()
  getTaxInfo()
  getMailSettings()
}
const columns = reactive([
  {
    title: 'Client Name',
    dataIndex: 'clientName',
    key: 'clientName'
  },
  {
    title: 'Account Pre Restructure',
    dataIndex: 'beforeAccount',
    key: 'beforeAccount'
  },
  {
    title: 'Account Post Restructure',
    dataIndex: 'afterAccount',
    key: 'afterAccount'
  },
  {
    title: 'Operator',
    dataIndex: 'opertator',
    key: 'opertator'
  },
  {
    title: 'Operate Date',
    dataIndex: 'opertateDate',
    key: 'opertateDate',
    customRender: ({ text }) => (text ? dayjs(text).format('YYYY-MM-DD') : '--')
  }
])
const data = ref([])
const visible = ref(false)
// 基础数据
const basicInfoData = ref({})
// bankInfo数据
const bankInfoData = ref({})
// payment settings 数据
const paymentSettings = ref({})
// taxInfo数据
const taxInfoData = ref({})
// Bank Info弹出框数据
const formState = ref({})
// 邮箱信息
const mailSettings = reactive({
  to: [],
  cc: []
})
/**
 * 获取基础数据
 */
const getBasicInfo = () => {
  loading1.value = true
  f.getBasicInfo(id)
    .then(res => {
      if (res.code === 2000) {
        basicInfoData.value = res.data
      }
    })
    .finally(() => {
      setTimeout(() => {
        loading1.value = false
      }, 30)
    })
}
/**
 * 获取 Billing Cycle 信息
 */
const getPaymentSettings = () => {
  loading2.value = true
  f.getPaymentSettings(id)
    .then(({ data }) => {
      paymentSettings.value = data
    })
    .finally(() => {
      loading2.value = false
    })
}
/**
 * 获取Bank Info数据
 */
const getBankInfo = () => {
  loading2.value = true
  f.getFinancialBank(id)
    .then(res => {
      if (res.code === 2000) {
        bankInfoData.value = res.data
      }
    })
    .finally(() => {
      getAccountHistory()
    })
}
/**
 * 编辑银行信息（先校验是否有合同）
 */
const editBankInfo = () => {
  loading2.value = true
  // 检查是否有合同
  f.getSignedCompany(id)
    .then(({ data }) => {
      if (Array.isArray(data) && data.length > 0) {
        router.push({ name: 'Bank Info' })
      } else {
        Modal.warning({
          title: 'Please add a contract first.'
        })
      }
    })
    .finally(() => {
      loading2.value = false
    })
}
/**
 * 获取Tax Info数据
 */
const getTaxInfo = () => {
  loading3.value = true
  f.getPaperInvoiceSettings(id)
    .then(res => {
      if (res.code === 2000) {
        taxInfoData.value = res.data
      }
    })
    .finally(() => {
      setTimeout(() => {
        loading3.value = false
      }, 30)
    })
}
/**
 * 获取Bank Info History数据
 */
const getAccountHistory = () => {
  f.getAccountHistory({
    clientID: id
  })
    .then(res => {
      if (res.code === 2000) {
        data.value = res.data
      }
    })
    .finally(() => {
      setTimeout(() => {
        loading2.value = false
      }, 30)
    })
}
/**
 * 获取Bank Info弹出框数据
 * @param id
 */
const showBankInfo = id => {
  f.getCollectionAccountInfo({
    CollectAccount: id
  }).then(res => {
    if (res.code === 2000) {
      visible.value = true
      formState.value = res.data
    }
  })
}
/**
 * 获取邮件设置
 */
const getMailSettings = () => {
  mailSettings.to.splice(0)
  mailSettings.cc.splice(0)
  f.getEmailSettings(id).then(({ data }) => {
    Object.keys(data).forEach(key => {
      if (key === 'mails') {
        data[key].forEach(item => {
          if (item.emailType === 1) {
            mailSettings.to.push(item.displayName)
          }
          if (item.emailType === 2) {
            mailSettings.cc.push(item.displayName)
          }
        })
      }
      if (key === 'toHistory') {
        data[key].forEach(item => {
          mailSettings.to.push(item.email)
        })
      }
      if (key === 'ccHistory') {
        data[key].forEach(item => {
          mailSettings.cc.push(item.email)
        })
      }
    })
  })
}
/**
 * 关闭弹出框
 */
const handleCancel = () => {
  visible.value = false
}
/**
 * 下载附件
 */
// 下载器
const downloadHandler = useDownload
const handleDownload = (addr, name) => {
  downloadHandler.showDownload([
    {
      ServerFileID: 2,
      Url: Config.SIGNAL_R_URL,
      RealPath: addr.replace('/\\/g', '\\\\'),
      FullName: `\\${name}`
    }
  ])
}
/**
 * 初始化
 */
onMounted(() => {
  getBasicInfo()
  getPaymentSettings()
  getBankInfo()
  getTaxInfo()
  getMailSettings()
})
</script>

<style lang="less" scoped>
@import '@/assets/style/reset_table';

@border: 1px solid @lighter-gray;
.table {
  border: @border;
  margin-top: 24px;
  .cell {
    padding: 10px 14px;
    border-bottom: @border;
    border-right: @border;
    &:last-child {
      border-right: none;
    }
    &.field {
      background-color: @milk;
      color: @text-gray;
    }
  }
  .ant-row:last-child {
    .cell {
      border-bottom: none;
    }
  }
  .ant-tag {
    background-color: @phase-default;
    border: none;
    padding: 1px 12px;
    font-size: 14px;
    .e-icon {
      color: @primary-color !important;
      cursor: pointer;
    }
  }
}
.ant-divider {
  border-top: 1px solid #dcdee7 !important;
}
.info-container {
  .ant-spin-nested-loading:not(:first-child) {
    .e-container {
      margin-top: 24px;
    }
  }
}
.primary-modal {
  .ant-input[disabled] {
    color: @text-black;
  }
  .information {
    width: 100%;
    min-height: 80px;
    border: 1px solid #e1e6f0;
    background-color: #f2f2f2;
    border-radius: 2px;
    padding-top: 7px;
    padding-left: 10px;
    color: #262626;
    margin-top: 6px;
    margin-bottom: 16px;
  }
}
</style>
<route lang="yaml">
name: Financial Information
path: '/client/:id/financial-information'
meta:
  sort: 50
  icon: Financial_Information
  permission: FinancialInformation
</route>
